package com.sinux.mms.common.init;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;


/**
 * 实现Application监听器,监听ContextRefreshedEvent<br>
 * 监听spring的上下文发布事件
 * @author w.g
 * @date 2019-08-02
 */
@SuppressWarnings("all")
@Service
public class ApplicationListenerInit implements ApplicationListener<ContextRefreshedEvent>{

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		
		if(event.getApplicationContext().getParent()==null) {
			try {
				System.out.println("=====监听上下文发布事件,初始化配置=====");
				ApplicationContext applicationContext = event.getApplicationContext();  
		        WebApplicationContext webApplicationContext = (WebApplicationContext)applicationContext;  
		        ServletContext servletContext = webApplicationContext.getServletContext();
		        //获取web.xml中的context-param参数
		        String dbType=servletContext.getInitParameter("dbType");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 读配置文件
	 */
	public void readProperties(ServletConfig config) {
		//编译后放置于class目录下
		String path = SpringInit.class.getResource("/conf/conf.properties").getPath(); 
		Properties prop=PropertiesUtil(path);
		
	}
	
	/**
	 * TODO 读取配置文件
	 * @param path 文件路径
	 */
	public Properties PropertiesUtil(String path) {
		//System.out.println(path);
		Properties properties = null;
		File f = new File(path);
		if(!f.exists()){
			return properties;
		}
		InputStream in = null;
		FileInputStream fileInputStream = null;
		
		if(f.getName().endsWith(".properties") && !f.isDirectory()){
			try{
				properties = new Properties();
				fileInputStream = new FileInputStream(f.getAbsolutePath());
				in = new BufferedInputStream(fileInputStream);
				properties.load(in);
				
			}catch (Exception ex) {
				// TODO: handle exception
				ex.printStackTrace();
			}finally {
				try{
					if(in != null){
						in.close();
					}
					if(fileInputStream != null){
						fileInputStream.close();
					}
				}catch (Exception eee) {
					// TODO: handle exception
					eee.printStackTrace();
				}
			}
		}
		return properties;
	}

}
